<template>
	<view class="page">
		<uni-nav-bar title="AI智能对话"  statusBar @clickLeft="goMine()">
			<view slot="left">
				<image src="../../static/image/mine.png" style="width: 60rpx;height: 60rpx;"></image>
			</view>
		</uni-nav-bar>
		<scroll-view class="list" :style="'height:calc(100vh - 170rpx - '+safeBottom+'px)'" scroll-y="true"
			:scroll-into-view="scrollIntoView" @scroll="scroll">
			<view style="height:20rpx"></view>
			<view class="li" v-for="(item,index) in list" :key="index">
				<view class="time"
					v-if="index===0||(index>1&&new Date(item.time).getTime() - new Date(list[index-1].time).getTime()>5000)">
					{{format(item.time)}}
				</view>
				<view class="answer" v-if="item.type ==='A'">
					<image class="head" src="@/static/image/logo4.png"></image>
					<view class="info">
						<view class="name">{{item.name}}</view>
						<view class="txt" v-if="!item.txt">
							<loading />
						</view>
						<view v-else class="txt" @longtap="copy(item.txt)">
							{{item.txt}}
						</view>
					</view>
				</view>
				<view class="question" v-if="item.type ==='Q'">
					<view class="info">
						<view class="name">{{item.name}}</view>
						<view class="txt" @longtap="copy(item.txt)">{{item.txt}}</view>
					</view>
					<image class="head" :src="Avatar" v-if="Avatar"></image>
					<view class="head iconfont icon-touxiang" v-else></view>
				</view>
			</view>
			<view id="maodian" class="maodian"></view>
		</scroll-view>
		<view class="bottom"  :style="{ bottom: bottomVal,'padding-bottom':safeBottom&&!bottomVal?safeBottom+'px':'20rpx' }">
			<view class="tools">
				<view class="tool" @click="goHistory()">
					<image class="icon" src="@/static/image/lishiduihua.png"></image>历史对话
				</view>
				<view class="tool" @click="goVip()">
					<image class="icon" src="@/static/image/crown.png"></image>开通会员
				</view>
			</view>
			<view class="sendBox" >
				<input type="text" :cursor-spacing="30" @focus="inputBindFocus" @blur="inputBindBlur"
					:adjust-position="false" v-model="txt" @input="input()" class="input" @keyboardheightchange="keyboardheightchange" placeholder-style="color:#999"
					placeholder="请输入消息...">
				<view class="send" @click="send()">发送</view>
			</view>
		</view>
	</view>
</template>
<script>
	import loading from '@/components/loading.vue'
	export default {
		components: {
			loading
		},
		data() {
			return {
				bottomVal:'',
				scrollIntoView: 'maodian',
				txt: '',
				list: [{
					type: 'A',
					name: 'AI包打听',
					txt: "请自觉遵守相关法律，不要提及（涉嫌）违反中国法律的问题，不要触碰政治敏感问题；否则一律封号处理。",
					time: new Date()
				}],
				safeBottom: uni.getStorageSync('safeBottom'),
				safeTop: uni.getStorageSync('safeTop') > 20 ? uni.getStorageSync('safeTop') * 2 : 66,
				clock: false,
				isAnswer: true,
				Avatar: uni.getStorageSync('Avatar')
			}
		},
		onShow() {
			uni.hideHomeButton()
		},
		onLoad: async function(option) {
			if (option.from == 'h') {
				const data = JSON.parse(decodeURIComponent(option.data))
				this.list.push({
					type: 'Q',
					name: uni.getStorageSync('wxName') || '我',
					txt: data.question,
					time: this.format(data.createTime)
				})
				this.list.push({
					type: 'A',
					name: 'AI包打听',
					txt: data.answer,
					time: this.format(data.createTime)
				})
			}
		},
		methods: {
			keyboardheightchange(e){
				console.log(e);
			},
			inputBindFocus(e) {
			        // 获取手机键盘的高度，赋值给input 所在盒子的 bottom 值
			        // 注意!!! 这里的 px 至关重要!!! 我搜到的很多解决方案都没有说这里要添加 px
					this.bottomVal =e.detail.height + 'px'
					
			    },
			    
			    inputBindBlur() {
			        // input 失去焦点，键盘隐藏，设置 input 所在盒子的 bottom 值为0
			        this.bottomVal =0
				
			    },
			copy(str) {
				uni.setClipboardData({
					data: str, //要被复制的内容
					success: () => { //复制成功的回调函数
						uni.showToast({ //提示
							title: '复制成功'
						})
					}
				})
			},
			input(e) {
				this.$nextTick(() => {
					this.txt = this.txt.replace(
						/[^\u4e00-\u9fa5a-zA-Z\d,\.，?？.<>《》[ ]''"":;{}[\|、】【、‘；“”‘’；：。，）（*&……%￥#@！~。]+/g, '')
				})
			},
			goHistory() {
				uni.navigateTo({
					url: '/pages/history/index'
				})
			},
			goVip() {

				if (!uni.getStorageSync('openid')) {
					uni.reLaunch({
						url: '/pages/login/index'
					})
					return
				}

				uni.navigateTo({
					url: '/pages/vip/index'
				})
			},
			goMine() {
				if (!uni.getStorageSync('openid')) {
					uni.reLaunch({
						url: '/pages/login/index'
					})
					return
				} else {
					uni.navigateTo({
						url: '/pages/mine/index'
					})
				}
			},
			scroll() {
				this.scrollIntoView = ''
			},
			async send(e) {
				if (!uni.getStorageSync('openid')) {
					uni.reLaunch({
						url: '/pages/login/index'
					})
					return
				}
				const that = this
				if (this.txt.trim() === '') {
					uni.showToast({
						title:'不能发送空白消息',
						icon:'none',
						duration:2000	
					})
					return
				}
				if (!this.isAnswer) {
					uni.showToast({
						title: '上一个问题尚未解答，请稍后再发起新的提问',
						icon: 'none',
						duration: 3000,
						mask: true
					})
					return false
				}
				this.list.push({
					type: 'Q',
					name: uni.getStorageSync('wxName') || '我',
					txt: this.txt,
					time: new Date()
				})
				that.scrollIntoView = ''
				setTimeout(() => {
					that.scrollIntoView = 'maodian'
				}, 10)
				const question = this.txt
				this.txt = ''
				// uni.showLoading(
				// {
				// 	title: '拼命思考中...',
				// })
				that.list.push({
					type: 'A',
					name: 'AI包打听',
					txt: '',
					time: new Date()
				})
				that.isAnswer = false
				const res = await this.$post('api/askQuestion', {
					question,
					openid: uni.getStorageSync('openid'),
					wxName: uni.getStorageSync('wxName')
				}, {
					"Content-Type": 'application/json'
				})
				console.log(res, 'sssdddd');
				if (res.status === 200) {
					if (res.data.status == 1 || res.data.status == 0) {
						setTimeout(() => {
							that.getAnswer(res.data.id)
						}, 3000)
						return
					}
					// uni.hideLoading()
					that.list.splice(that.list.length - 1, 1, {
						type: 'A',
						name: 'AI包打听',
						txt: res.data.answer,
						time: res.data.answerTime
					})
					that.isAnswer = true
					that.scrollIntoView = ''
					setTimeout(() => {
						that.scrollIntoView = 'maodian'
					}, 10)
					that.clock = false
					clearInterval(that.clock)
				} else {
					// uni.hideLoading()
					that.clock = false
					that.isAnswer = true
					clearInterval(that.clock)
					uni.showToast({
						title: res.error,
						duration: 3000,
						icon: 'none'
					})
				}
			},
			async getAnswer(questionId) {
				const that = this
				const res = await this.$post('api/getQuestionAnswer', {
					questionId,
					openid: uni.getStorageSync('openid')
				}, {
					"Content-Type": 'application/json'
				})
				if (res.status === 200) {
					if (res.data.status == 0 || res.data.status == 1) {
						setTimeout(() => {
							that.getAnswer(res.data.id)
						}, 3000)
						return
					}
					that.list.splice(that.list.length - 1, 1, {
						type: 'A',
						name: 'AI包打听',
						txt: res.data.answer,
						time: res.data.answerTime
					})
					// uni.hideLoading()
					that.scrollIntoView = ''
					setTimeout(() => {
						that.scrollIntoView = 'maodian'
					}, 10)
					that.clock = false
				} else {
					// uni.hideLoading()
				}
			},
			format(dat) {
				dat = new Date(dat)
				//获取年月日，时间
				var year = dat.getFullYear();
				var mon = (dat.getMonth() + 1) < 10 ? "0" + (dat.getMonth() + 1) : dat.getMonth() + 1;
				var data = dat.getDate() < 10 ? "0" + (dat.getDate()) : dat.getDate();
				var hour = dat.getHours() < 10 ? "0" + (dat.getHours()) : dat.getHours();
				var min = dat.getMinutes() < 10 ? "0" + (dat.getMinutes()) : dat.getMinutes();
				var seon = dat.getSeconds() < 10 ? "0" + (dat.getSeconds()) : dat.getSeconds();
				var newDate = year + "-" + mon + "-" + data + " " + hour + ":" + min + ":" + seon;
				return newDate;
			}
		}
	}
</script>
<style scoped lang="scss">
	* {
		margin: 0;
		padding: 0;
	}

	.page {
		width: 100vw;
		height: 100vh;
		background-color: #F3F4F6;
		position: relative;
		overflow-y: scroll;

		.list {
			width: 100%;
			height: 100vh;
			background-color: #F3F4F6;
			overflow-y: auto;
			// padding: 65px 0 180rpx;
			box-sizing: border-box;

			.li {
				padding-bottom: 30rpx;

				.time {
					font-size: 20rpx;
					color: #999;
					text-align: center;
					margin-bottom: 20rpx;
				}

				.answer,
				.question {
					width: 100vw;
					text-align: left;
					display: flex;
					// align-items: center;
					justify-content: flex-start;

					.head {
						width: 80rpx;
						height: 80rpx;
						border-radius: 50%;
						background-color: #fff;
						margin: 0 20rpx;
						font-size: 60rpx;
						text-align: center;
						line-height: 80rpx;
					}

					.info {
						width: 70vw;
					}

					.name {
						color: #999;
						margin-bottom: 10rpx;
						font-size: 20rpx;
					}

					.txt {
						display: inline-block;
						max-width: 70vw;
						padding: 20rpx;
						border-radius: 0 20rpx 20rpx 20rpx;
						text-align: justify;
						color: #000;
						background-color: #fff;
						font-size: 28rpx;
						letter-spacing: 2rpx;
						white-space: pre-wrap;
					}
				}

				.question {
					width: 100vw;
					display: flex;
					align-items: center;
					justify-content: flex-end;

					.txt {
						border-radius: 20rpx 0 20rpx 20rpx;
					}

					.info {
						text-align: right;
					}
				}
			}

			.maodian {
				height: 200rpx;
			}
		}

		.bottom {
			background-color: #fff;
			width: 100%;
			height: 150rpx;
			padding-top: 20rpx;
			position: absolute;
			left: 0;
			bottom: 0;

			.tools {
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;
				padding-left: 20rpx;

				.tool {
					display: flex;
					align-items: center;
					font-size: 20rpx;
					width: 182rpx;
					height: 56rpx;
					background: #FFFFFF;
					box-shadow: 0px 4rpx 16rpx 0px rgba(0, 0, 0, 0.08);
					border-radius: 28rpx;
					justify-content: center;
					margin-right: 20rpx;

					.icon {
						width: 28rpx;
						height: 28rpx;
						margin-right: 10rpx;
					}
				}
			}

			.sendBox {
				width: calc(100% - 40rpx);
				margin: auto;
				display: flex;
				align-items: center;
				justify-content: space-between;
				
				.input {
					width: 522rpx;
					height: 72rpx;
					background: #F8F8F8;
					border-radius: 16rpx;
					padding-left: 20rpx;
					font-size: 32rpx;
					font-family: PingFangSC-Regular, PingFang SC;
					font-weight: 400;
					line-height: 72rpx;
				}

				.send {
					font-size: 32rpx;
					width: 144rpx;
					height: 72rpx;
					background: linear-gradient(222deg, #2CE6FF 0%, #2A87FF 100%);
					border-radius: 36rpx;
					color: #fff;
					text-align: center;
					line-height: 72rpx;
				}
			}
		}
	}
</style>
